const UserModel = require('../db/models/user');


class UserService { 
  //添加
  async addUser (data) {
    //检查cid是否存在 check cid is existed
    const uid = data.uid;
    const result = await UserModel.findOne({ where: { uid } });

    //判断 check
    if (result) { 
      //更新 update  
      return await UserModel.update(data, {where: { uid }})
    }else {
      //创建 create
      return await UserModel.create(data);
    }
  }

  async updateUser (data, userId) {
    return await UserModel.update(data, { where: { id: userId }});
  }

  //查询
  async findUserById (userId) {
    return await UserModel.findOne({
      where: { id: userId }
    });
  }

  //检查
  async loginCheckInfo (userInfo) {
    const { uid, password } = userInfo;
    //查询
    const result = await UserModel.findOne({
      where: { uid }
    });

    if(!result) {
      return 10003; //不存在
    }

    const dbPassword = result.get('password');
    const id = result.get('id');
    if(password !== dbPassword) {
      return 10004; //密码错误
    }

    const nickname = result.get('nickname');

    return {
      id,
      uid,
      nickname
    }
  }
}

module.exports = new UserService();